package com.zys.el.time.controller;


import com.alibaba.fastjson2.JSON;
import com.zys.el.time.common.Result;
import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.dto.ScrollPage;
import com.zys.el.time.entity.Thinking;
import com.zys.el.time.service.CommentService;
import com.zys.el.time.service.ThinkingLikeService;
import com.zys.el.time.service.ThinkingService;
import com.zys.el.time.service.lambda_like.ILambdaLikeService;
import com.zys.el.time.vojo.ThinkingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/thinking")
@CrossOrigin
@Api(tags = "帖子接口")
public class ThinkingController { // TODO 对当前用户做校验是否是有权限用户或是否是自己
    @Autowired
    private ThinkingService thinkingService;
    @Resource
    private CommentService commentService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ILambdaLikeService thinkLikeService;

    @GetMapping("")
    @ApiOperation(value = "查询帖子By帖子id")
    @ApiImplicitParam(name = "thinkingId", value = "帖子id", required = true)
    public Result<ThinkingVo> getByThinkingId(@RequestParam("thinkingId") String thinkingId) {
        log.debug(thinkingId);
        if (CheckUtil.isNotPass(thinkingId)) return Result.fail("参数有误");
        ThinkingVo thinkingVo = thinkingService.getThinkingVoById(Long.valueOf(thinkingId));
        System.out.println(thinkingVo);
        return Result.ok(thinkingVo);
    }

    @GetMapping("/page")
    @ApiOperation(value = "获取帖子列表By频道id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId", value = "频道id", required = true),
            @ApiImplicitParam(name = "max", value = "上一页的最小值", required = true),
            @ApiImplicitParam(name = "offset", value = "上一页最小值的数量", required = true),
            @ApiImplicitParam(name = "size", value = "页大小", required = true)
    })
    public Result getPageByChannelId(@RequestParam("channelId") String channelId,
                                     @RequestParam("max") String max,
                                     @RequestParam("offset") Integer offset,
                                     @RequestParam("size") Integer size) {
        log.debug("{},{},{},{}", channelId, max, offset, size);
        if (CheckUtil.isNotPass(channelId, max)) return Result.fail("参数有误");
        if (StringUtils.isBlank(channelId) || StringUtils.isBlank(max) || offset == null || size == null)
            return Result.fail("缺少参数");
        ScrollPage<ThinkingVo> scrollPage = thinkingService.getPageByChannelId(Long.valueOf(channelId), Long.valueOf(max), offset, size);
        return Result.ok(scrollPage);
    }

    @PostMapping("/add")
    @ApiOperation("发布帖子")
    public Result addThinking(@RequestBody Thinking thinking) {
        log.debug(String.valueOf(thinking));
        if (CheckUtil.isNotPass(thinking.getText())) return Result.fail("参数有误");
        boolean b = thinkingService.saveAndReview(thinking);
        if (b) {
            return Result.ok("发布成功");
        }
        return Result.fail("发布失败");
    }

    @PostMapping("/modify")
    @ApiOperation("修改帖子")
    public Result modifyThinking(@RequestBody Thinking thinking) {
        if (thinking.getThinkingId() == null) return Result.fail("参数有误");
        thinkingService.updateWithCheckUser(thinking);
        return Result.ok("修改成功");
    }

    @DeleteMapping("/del/{thinkingId}")
    @ApiOperation("删除帖子")
    @ApiImplicitParam(name = "thinkingId", value = "帖子id", required = true)
    public Result delThinking(@PathVariable String thinkingId,
                              @RequestParam("channelId") String channelId) {
        log.debug(thinkingId, channelId);
        if (CheckUtil.isNotPass(thinkingId, channelId)) return Result.fail("参数有误");
        boolean b = thinkingService.removeById(thinkingId);
        String key = RedisConstants.PAGE_THINKING_KEY + channelId;
        stringRedisTemplate.opsForZSet().remove(key, thinkingId);
        if (b) {
            return Result.ok("删除成功");
        }
        return Result.fail("删除失败");
    }

    @GetMapping("otherInfo")
    public Result getThinkingOtherInfo(@RequestParam("thinkingId") String thinkingId,
                                       @RequestParam("userId") String userId) {
        log.debug(String.valueOf(thinkingId));
        if (CheckUtil.isNotPass(thinkingId, userId)) return Result.fail("参数有误");
        HashMap<String, Object> m = new HashMap<>();
        // 点赞数量
        Long likeCount = thinkLikeService.getLikeCount(Long.valueOf(thinkingId));
        // 是否点赞
        boolean isLike = thinkLikeService.getUserIsLike(Long.valueOf(thinkingId), Long.valueOf(userId));
        // 评论数量
        Long commentCount = commentService.query().eq("thinking_id", thinkingId).count();

        m.put("likeCount", likeCount);
        m.put("isLike", isLike);
        m.put("commentCount", commentCount);
        m.put("collectCount", 0);

        return Result.ok(m);
    }

    @GetMapping("otherInfoList")
    public Result getThinkingOtherInfoList(@RequestParam("thinkingIds") String thinkingIds,
                                           @RequestParam("userId") String userId) {
        log.debug(String.valueOf(thinkingIds));
        if (CheckUtil.isNotPass(thinkingIds, userId)) return Result.fail("参数有误");
        List<String> thinkingIdList = JSON.parseObject(thinkingIds, List.class);
        HashMap<String, Map<String, Object>> map = new HashMap<>();

        Long uid = Long.valueOf(userId);

        thinkingIdList.forEach(t -> {
            HashMap<String, Object> m = new HashMap<>();
            // 点赞数量
            Long likeCount = thinkLikeService.getLikeCount(Long.valueOf(t));
            // 是否点赞
            boolean isLike = thinkLikeService.getUserIsLike(Long.valueOf(t), uid);
            // 评论数量
            Long commentCount = commentService.query().eq("thinking_id", t).count();

            m.put("likeCount", likeCount);
            m.put("isLike", isLike);
            m.put("commentCount", commentCount);
            m.put("collectCount", 0);
            map.put(t, m);
        });

        return Result.ok(map);
    }
}
